/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.fzhucc.modules.question.service;

import com.fzhucc.exception.BadRequestException;
import com.fzhucc.modules.question.domain.QuestionByUser;
import com.fzhucc.modules.question.domain.dto.QuestionByUserDto;
import com.fzhucc.modules.question.domain.dto.QuestionByUserQueryCriteria;
import com.fzhucc.modules.question.domain.dto.QuizDto;
import com.fzhucc.modules.question.repository.QuestionByUserRepository;
import com.fzhucc.modules.question.service.mapstruct.QuestionByUserMapper;
import com.fzhucc.utils.*;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.*;

/**
 * @author yyg
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2023-03-02
 **/
@Service
@RequiredArgsConstructor
public class QuestionByUserService {

    private final QuestionByUserRepository questionByUserRepository;
    private final QuestionByUserMapper questionByUserMapper;

    public Map<String, Object> queryAll(QuestionByUserQueryCriteria criteria, Pageable pageable) {
        Page<QuestionByUser> page = questionByUserRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return PageUtil.toPage(page.map(questionByUserMapper::toDto));
    }

    public List<QuestionByUserDto> queryAll(QuestionByUserQueryCriteria criteria) {
        return questionByUserMapper.toDto(questionByUserRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    public QuestionByUserDto findById(Integer id) {
        QuestionByUser questionByUser = questionByUserRepository.findById(id).orElseGet(QuestionByUser::new);
        ValidationUtil.isNull(questionByUser.getId(), "QuestionByUser", "id", id);
        return questionByUserMapper.toDto(questionByUser);
    }

    @Transactional(rollbackFor = Exception.class)
    public QuestionByUserDto create(QuestionByUser resources) {
        return questionByUserMapper.toDto(questionByUserRepository.save(resources));
    }

    @Transactional(rollbackFor = Exception.class)
    public void update(QuestionByUser resources) {
        QuestionByUser questionByUser = questionByUserRepository.findById(resources.getId()).orElseGet(QuestionByUser::new);
        ValidationUtil.isNull(questionByUser.getId(), "QuestionByUser", "id", resources.getId());
        questionByUser.copy(resources);
        questionByUserRepository.save(questionByUser);
    }

    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            questionByUserRepository.deleteById(id);
        }
    }

    public QuestionByUserDto quiz(QuizDto dto) {
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {
            throw new BadRequestException("用户ID未找到");
        }
        QuestionByUser resources = new QuestionByUser();
        resources.setUserId(userId);
        resources.setPhone(dto.getPhone());
        resources.setName(dto.getName());
        resources.setQuestion(dto.getQuestion());
        resources.setSubmissionTime(new Timestamp(new Date().getTime()));
        QuestionByUser res = questionByUserRepository.save(resources);
        return questionByUserMapper.toDto(res);
    }

    public void download(List<QuestionByUserDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (QuestionByUserDto questionByUser : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("提交的问题", questionByUser.getQuestion());
            map.put("用户", questionByUser.getUserId());
            map.put("提交时间", questionByUser.getSubmissionTime());
            map.put("联系方式", questionByUser.getPhone());
            map.put("姓名", questionByUser.getName());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}